# encoding=utf-8
#from DriverAndUnit.HTMLTestRunner import HTMLTestRunner
from DriverAndUnit.HTMLTestRunnerCN import HTMLTestRunner
from email.mime.text import MIMEText
import smtplib
import unittest
import time,os
from LbtFront.TestCase.login_case import loginTest
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#==============邮件接收者=================
mailreceivers=['15093131283@139.com']
#==============发送人邮箱=================
mail_host='smtp.163.com'
mail_port='25'
mail_user='15093131283@163.com'
mail_pass='yangdawei1990'
#=============发邮件功能=================
def send_mail(mailreceivers,file_new):
    '''
    :param mailreceivers:接收人列表
    :param file_new:文件名
    :return:true或者false
    '''
    f=open(file_new,'rb')
    mail_body=f.read()
    f.close()
    msg=MIMEText(mail_body,'html','utf-8')
    msg['Subject']='自动化测试报告'
    msg['From']=mail_user
    msg['To']=';'.join(mailreceivers)
    try:
        s=smtplib.SMTP()
        s.connect(mail_host,mail_port)
        s.login(mail_user,mail_pass)
        s.sendmail(mail_user,mailreceivers,msg.as_string())
        s.close()
        return True

    except Exception as e:
        print(str(e))
        return False
#===================查找测试报告目录，生成测试报告==================
def new_report(testreport):
    lists=os.listdir(testreport)
    lists.sort(key=lambda fn:os.path.getatime(testreport+'\\'+fn))
    file_new=os.path.join(testreport,lists[-1])
    print(file_new)
    return file_new

if __name__=="__main__":
    now=time.strftime("%Y-%m-%d %H_%M_%S")
    filename='./../report/reportHTML/'+now+"result.html"
    fp=open(filename,'wb')
    runner=HTMLTestRunner(stream=fp,title='乐贝通front自动化测试报告',description='环境 ：window 7 浏览器：firefox')
    '''两种加载测试用例的方式'''
    discover=unittest.defaultTestLoader.discover('./../LbtFront/TestCase',pattern='*_case.py')
    #suite=unittest.makeSuite(loginTest)
    runner.run(discover)
    fp.close()
    filepath=new_report('./../report/reportHTML/')
    if send_mail(mailreceivers,filepath):
        print('发送邮件成功')
    else:
        print("发送邮件失败")